<?php

namespace app\api\controller;

use app\admin\model\Captcha;
use app\admin\model\Members;
use app\home\validate\Reg;

use Qiniu\Auth;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;

/**
 * 首页相关
 */
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
class Home extends Base
{
    public function _initialize()
    {
        $uid = \request()->post('uid');
        $token = \request()->post('token');
        check_token($uid, $token);
    }

    /**
     * 创建房间
     */
    public function create_room(Request $request){
        $uid           = $request->post('uid');
        $key_words     = $request->post('key_words');
        $room_password = $request->post('room_password');
        if(!$key_words){
            json_return(204,'缺少参数');
        }
        $user_info = Db::name('member')->field('id,is_room')->where('id',$uid)->find();
        if(!$user_info['is_room']){
            json_return(201,'暂无权限创建房间');
        }
        $arr   = [];
        $arr[] = $uid;
        $insert = [
            'key_words'=>$key_words,
            'uid'      =>$uid,
            'managers' =>json_encode($arr),
            'room_number'=>'2'.rand(111,999).rand(11111,99999)
        ];
        if($room_password){
            $insert['room_password'] = $room_password;
        }
        $room_id  = Db::name('chatroom')->insertGetId($insert);
        $config   = config('tencent');
        $end_time = date('Y-m-d H:i:s',strtotime("+5 month"));

        if(is_numeric($room_id )) {
            $data['push_url'] = getPushUrl($config['bizid'], $room_id, $config['key'], $end_time);
            $data['play_url'] = getPlayUrl($config['bizid'], $room_id);
            Db::name('chatroom')->where('id',$room_id)->update($data);
        }
        $chat_info =  Db::name('chatroom')->where('id',$room_id)->find();
        if($room_id){
            json_return(200,'创建聊天室成功',$chat_info);
        }
    }

    /**
     * 连续签到天数
     */
    public function sign_famous(Request $request){
        $uid   = $request->post('uid');
        $date  = date('Y-m-01');
        $map['uid']  = $uid;
        $map['date'] = array('gt',$date);
        $days = Db::name('sign_in')->where($map)->order('id desc')->column('date');
        if(!$days){
            $days=0;
        }else{
            foreach ($days as $k=>$v){
                $days[$k] = strtotime($v);
            }
            $days = continue_day($days);
        }
        $data =Db::name('sign_in')->where($map)->column('date');
        $today = date('Y-m-d');
        if(in_array($today,$data)){
            $back['is_sign'] = 1;
        }else{
            $back['is_sign'] = 0;
        }
        $back['days'] = $days;
        $back['data'] = $data;
        json_return(200,'成功',$back);
    }

    /**
     * 签到操作
     */
    public function sign_in(Request $request){
        $uid  = $request->post('uid');
        $date = date('Y-m-d');
        $map['uid']  = $uid;
        $map['date'] = $date;
        $is_sign     = Db::name('sign_in')->where($map)->find();
        if($is_sign){
            json_return(201,'已经签过到了');
        }else{
            $insert = [
                'uid'  =>$uid,
                'date' =>$date,
            ];
        Db::name('sign_in')->insert($insert);
        json_return(200,'成功');
        }
    }

    /**
     * 获取首页聊天室
     */
    public function get_chatroom_info(Request $request){
        $uid       = $request->post('uid');
        $page      = $request ->post('page')?$request->post('page'):1;
        $limit     = 20;
        $start     = ($page-1)*$limit;
        $key_words = trim($request ->post('key_words'));
        $chat_id      = $request ->post('chat_id');
        $search_uid   = $request ->post('search_uid');
        $w = [];
        if($key_words){
            $w['key_words'] = ['like','%'.$key_words.'%'];
        }
        if($chat_id){
            $w['id'] = $chat_id;
        }
        if($search_uid){
            $w['uid'] = $search_uid;
        }
        $data = Db::name('chatroom')
            ->limit($start,$limit)
            ->where($w)
            ->order('id desc')
            ->select();
        $my_fans = Db::name('attention')->where('boss_uid',$uid)->column('fans_uid');
        foreach ($data as $kk=>$vv){
            $user_info = Db::name('member')
                ->field('id,nickname,head')
                ->where('id',$vv['uid'])
                ->find();
            $data[$kk]['user_info'] = $user_info;
            if(in_array($vv['uid'],$my_fans)){
                $data[$kk]['is_attention'] = 1;
            }else{
                $data[$kk]['is_attention'] = 0;
            }
            $insert = [
                'chat_id' =>$chat_id
            ];
            $black_info = Db::name('black')->where($insert)->column('uid');
            $data[$kk]['black_info'] = $black_info;
        }
        $count = Db::name('chatroom')
            ->count();
        if(!$data){
            json_return(205,'暂无数据');
        }
        $return_data['back_data']  = $data;
        $return_data['now_page']   = $page;
        $return_data['per_page']   = $limit;
        $return_data['total_page'] = ceil($count/$limit);
        json_return(200,'成功',$return_data);
    }

    /**
     * 获取礼物信息
     */
    public function get_gift_info(Request $request){
        $page    = $request ->post('page')?$request->post('page'):1;
        $limit   = 20;
        $start   = ($page-1)*$limit;
        $data = Db::name('gift')
            ->limit($start,$limit)
            ->order('id desc')
            ->select();
        $count = Db::name('gift')
            ->count();
        if(!$data){
            json_return(205,'暂无数据');
        }
        $return_data['back_data']  = $data;
        $return_data['now_page']   = $page;
        $return_data['per_page']   = $limit;
        $return_data['total_page'] = ceil($count/$limit);
        json_return(200,'成功',$return_data);
    }

    /**
     * 获取音乐信息
     */
    public function get_music_info(Request $request){
        $page    = $request ->post('page')?$request->post('page'):1;
        $limit   = 20;
        $start   = ($page-1)*$limit;
        $data = Db::name('music')
            ->limit($start,$limit)
            ->order('id desc')
            ->select();
        $count = Db::name('gift')
            ->count();
        if(!$data){
            json_return(205,'暂无数据');
        }
        $return_data['back_data']  = $data;
        $return_data['now_page']   = $page;
        $return_data['per_page']   = $limit;
        $return_data['total_page'] = ceil($count/$limit);
        json_return(200,'成功',$return_data);
    }

    /**
     * 赠送房主礼物
     */
    public function send_gift(Request $request){
        $uid     = $request->post('uid');
        $r_uid   = $request->post('r_uid');
        $gift_id = $request->post('gift_id');
        if(!$uid || !$r_uid || !$gift_id){
            json_return(204,'缺少参数');
        }
        $gift_info  = Db::name('gift')->where('id',$gift_id)->find();
        $gift_money = $gift_info['gift_price'];
        $balance    = Db::name('member')->where('id',$uid)->value('money');
        if($gift_money>$balance){
            json_return(207,'余额不足');
        }
        Db::startTrans();
        try {
            //送礼物者减钱
            Db::name('member')->where('id',$uid)->setDec('money',$gift_money);
            addDetail($uid,$gift_money,3);

            //房主加钱
            Db::name('member')->where('id',$r_uid)->setInc('money',$gift_money);
            addDetail($r_uid,$gift_money,4);
            //添加订单数据
            $insert = [
               'uid'=>$uid,
               'r_uid'=>$r_uid,
               'gift_id'=>$gift_id,
               'money'=>$gift_money,
            ];
            Db::name('order')->insert($insert);
            Db::commit();
            json_return(200,'送礼物成功');
        }catch (\Exception $e){
            Db::rollback();
            json_return(500,'送礼物失败');
        }


    }

    /**
     * 发红包
     */
    public function send_red(Request $request){
        $uid      = $request->post('uid');
        $number   = $request->post('number');
        $money    = $request->post('money');
        $message  = $request->post('message');
        if(!$uid || !$number ||!$money ||!$message){
            json_return(204,'缺少参数');
        }

        $member_info = Db::name('member')->where('id',$uid)->find();
        if($member_info['money']<$money){
            json_return(201,'余额不足');
        }
        try {
            //发红包者减钱
            Db::name('member')->where('id',$uid)->setDec('money',$money);
            //添加订单数据
            $insert = [
                'uid'    =>$uid,
                'message'=>$message,
                'money'  =>$money,
                'number' =>$number
            ];
            $red_id = Db::name('red')->insertGetId($insert);
            $red_arr = send_red($money,$number);
            Cache::set('red_'.$red_id,$red_arr);
            $red_info = Db::name('red')->where('id',$red_id)->find();
            addDetail($uid,$money,5,$red_id);
            Db::commit();
            json_return(200,'发红包成功',$red_info);
        }catch (\Exception $e){
            Db::rollback();
            json_return(201,'发红包失败');
        }




    }

    /**
     * 抢红包
     */
    public function rob_red(Request $request){
        $uid         = $request->post('uid');
        $red_id      = $request->post('red_id');
        if(!$uid || !$red_id){
            json_return(204,'缺少参数');
        }
        $maps = [
            'uid'   =>$uid,
            'red_id'=>$red_id
        ];
        $is_rob       = Db::name('red_rob')->where($maps)->find();

        $rob_red_info = Db::name('red_rob')
            ->alias('r')
            ->field('r.*,m.head,m.nickname')
            ->join('dl_member m','m.id=r.uid')
            ->where('r.red_id',$red_id)
            ->select();
        if($is_rob){
            json_return(200,'红包列表',$rob_red_info);
        }
        $red_info  = Cache::get('red_'.$red_id);
        if(empty($red_info)){
            json_return(200,'红包已被抢完',$rob_red_info);
        }
        try {
            $rob_money = array_pop($red_info);
            Cache::set('red_'.$red_id,$red_info);
            //抢红包者加钱
            Db::name('member')->where('id',$uid)->setInc('money',$rob_money);
            addDetail($uid,$rob_money,6,$red_id);
            //添加抢红包记录
            $insert = [
                'uid'    =>$uid,
                'money'  =>$rob_money,
                'red_id' =>$red_id,
            ];
            Db::name('red_rob')->insert($insert);
           //更新红包
            Db::name('red')->where('id',$red_id)->setInc('rob',$rob_money);
            Db::name('red')->where('id',$red_id)->setInc('rob_number',1);
            $rob_red_info = Db::name('red_rob')
                ->alias('r')
                ->field('r.*,m.head,m.nickname')
                ->join('dl_member m','m.id=r.uid')
                ->where('r.red_id',$red_id)
                ->select();
            Db::commit();
            json_return(200,'抢红包成功',$rob_red_info);
        }catch (\Exception $e){
            Db::rollback();
            json_return(201,'红包已被抢完');
        }

    }

    /**
     * 加入聊天室
     */
    public function join_chatroom(Request $request){
          $uid      = $request->post('uid');
          $chat_id  = $request->post('chat_id');
          if(!$uid || !$chat_id){
                json_return(204,'缺少参数');
          }
          $chat_arr = Cache::get('chatroom_'.$chat_id);
          if(empty($chat_arr)){
              $chat_arr   = [];
              $chat_arr[] = $uid;
              Cache::set('chatroom_'.$chat_id,$chat_arr);
          }else{
              $chat_arr[] = $uid;
              $chat_arr = array_unique($chat_arr);
              $chat_arr = array_values($chat_arr);
              Cache::set('chatroom_'.$chat_id,$chat_arr);
          }
         $data_arr = Cache::get('chatroom_'.$chat_id);
         $map = [
              'id'=>array('in',$data_arr)
         ];
         $back_data = Db::name('member')
             ->field('id,nickname,head')
             ->where($map)
             ->select();
        json_return(200,'加入聊天室成功',$back_data);
    }

    /**
     * 退出聊天室
     */
    public function abort_chatroom(Request $request){
        $uid      = $request->post('uid');
        $chat_id  = $request->post('chat_id');
        if(!$uid || !$chat_id){
            json_return(204,'缺少参数');
        }
        $chat_arr = Cache::get('chatroom_'.$chat_id);
        if(!$chat_arr){
            json_return(200,'退出聊天室成功');
        }else{
            foreach ($chat_arr as $kk=>$vv){
                if($uid==$vv){
                    unset($chat_arr[$kk]);
                }
            }
        $chat_arr_new = array_values($chat_arr);
        Cache::set('chatroom_'.$chat_id,$chat_arr_new);
        //退出麦序
        $chatqueue_arr = Cache::get('chatqueue_arr'.$chat_id);
        if($chatqueue_arr) {
            foreach ($chatqueue_arr as $kk => $vv) {
                if ($vv == $uid) {
                    unset($chatqueue_arr[$kk]);
                }
            }
            $queue_arr = array_values($chatqueue_arr);
            Cache::set('chatqueue_arr' . $chat_id, $queue_arr);
        }
        json_return(200,'退出聊天室成功');
        }
    }

    /**
     * 获取聊天室用户列表
     */
    public function get_room_list(Request $request){
        $chat_id = $request->post('chat_id');
        $data_arr = Cache::get('chatroom_'.$chat_id);
        $map = [
            'id'=>array('in',$data_arr)
        ];
        $back_data = Db::name('member')
            ->field('id,nickname,head')
            ->where($map)
            ->select();
        json_return(200,'获取聊天室列表成功',$back_data);
    }

    /**
     * 申请禁言和创建聊天室
     */
    public function do_apply(Request $request){
        $uid = $request->post('uid');
        $way = $request->post('way');
        if(!$uid || !$way){
            json_return(201,'缺少参数');
        }
        $insert = [
            'uid'=>$uid,
            'way'=>$way
        ];
        $apply_info = Db::name('apply')->where($insert)->find();
        if($apply_info){
            if($apply_info['status']==1){
                json_return(201,'审核中');
            }
            if($apply_info['status']==2){
                json_return(201,'已审核成功');
            }
        }
        $result     = Db::name('apply')->insert($insert);
        if($result){
            json_return(200,'申请成功');
        }else{
            json_return(201,'申请失败');
        }
    }

    /**
     * 设置聊天室麦序
     */
    public function set_chatroom_queue(Request $request){
        $uid     = $request->post('uid');
        $queue   = $request->post('queue');
        $chat_id = $request->post('chat_id');
        $chat_uid = Db::name('chatroom')->where('id',$chat_id)->value('uid');
        if($uid!=$chat_uid){
            json_return(201,'您不管理人员,无法排序');
        }
        $queue_arr = json_decode($queue,true);
        $data = Db::name('member')
            ->field('id,nickname,head')
            ->where('id','in',$queue_arr)
            ->select();
        Cache::set('chatqueue_'.$chat_id,$data);
        json_return(200,'麦序排序成功',$data);
    }

    /**
     * 获取聊天室麦序
     */
    public function get_chatroom_queue(Request $request){
        $chat_id = $request->post('chat_id');
        $queue   = Cache::get('chatqueue_arr'.$chat_id);
        if(!$queue){
            $queue="";
        }
        json_return(200,'获取麦序成功',$queue);
    }

    /**
     * 抢麦
     */
    public function rob_chatroom_queue(Request $request){
        $uid     = $request->post('uid');
        $chat_id = $request->post('chat_id');
        $chatqueue_arr = Cache::get('chatqueue_arr'.$chat_id);
        if(!$chatqueue_arr){
            $chatqueue_arr = [];
            $chatqueue_arr[] = $uid;
        }else{
            $chatqueue_arr[] = $uid;
        }
        $queue_arr = array_unique($chatqueue_arr);
        $queue_arr = array_values($queue_arr);
        Cache::set('chatqueue_arr'.$chat_id,$queue_arr);
        json_return(200,'抢麦成功',$queue_arr );
    }

    /**
     * 下麦
     */
    public function down_chatroom_queue(Request $request){
        $uid     = $request->post('uid');
        $chat_id = $request->post('chat_id');
        $chatqueue_arr = Cache::get('chatqueue_arr'.$chat_id);
        foreach ($chatqueue_arr as $kk=>$vv){
            if($vv==$uid){
                unset($chatqueue_arr[$kk]);
            }
        }
        $queue_arr = array_values($chatqueue_arr);
        Cache::set('chatqueue_arr'.$chat_id,$queue_arr);
        json_return(200,'下麦成功',$queue_arr );
    }

    /**
     * 管理人员下麦
     */
    public function manager_down_chatroom_queue(Request $request){
        $uid         = $request->post('uid');
        $down_uid    = $request->post('down_uid');
        $chat_id     = $request->post('chat_id');
        $chat_uid = Db::name('chatroom')->where('id',$chat_id)->value('uid');
        if($uid!=$chat_uid){
            json_return(201,'您不管理人员,强制下麦');
        }
        $chatqueue_arr = Cache::get('chatqueue_arr'.$chat_id);
        foreach ($chatqueue_arr as $kk=>$vv){
            if($vv==$down_uid){
                unset($chatqueue_arr[$kk]);
            }
        }
        $queue_arr = array_values($chatqueue_arr);
        Cache::set('chatqueue_arr'.$chat_id,$queue_arr);
        json_return(200,'下麦成功',$queue_arr );
    }

    /**
     * 获取七牛云token
     */
    public function get_qiniu_token(){
        $qiniu_config = config('qiniu');
        $accessKey    = $qiniu_config['ACCESSKEY'];
        $secretKey    = $qiniu_config['SECRETKEY'];

        $auth  = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($qiniu_config['bucket']);
        $back = [
            'token' =>$token,
            'domain'=>$qiniu_config['domain']
        ];
        json_return(200,'成功',$back);
    }

    /**
     * 修改聊天室背景图
     */
    public function edit_chatroom_background(Request $request){
        $uid         = $request->post('uid');
        $chat_id     = $request->post('chat_id');
        $maps0 = [
            'uid'=>$uid,
            'id' =>$chat_id
        ];
        $chat_info = Db::name('chatroom')->where($maps0)->find();
        if(!$chat_info){
            json_return(201, '未查到房间信息');
        }
        if(!$uid ||!$chat_id){
            json_return(201, '缺少参数');
        }
        $result =  $this->qi_niu_upload();
        if($result['status']==1){
            $back['back_url'] = $result['msg'];
            Db::name('chatroom')->where('id',$chat_id)->update($back);
            json_return(200, '修改房间背景成功',$back);
        }else{
            json_return(200, '修改房间背景失败');
        }
    }

    /**
     * 开启或者关闭抢麦模式
     */
    public function open_rob(){
        $chat_id     =  input('post.chat_id');
        $is_open     =  input('post.is_open');
        $uid         =  input('post.uid');
        if(!in_array($is_open,[0,1])){
            json_return(201,'参数有误');
        }
        if(!$uid ||!$chat_id){
            json_return(204,'缺少参数');
        }
        $maps = [
            'uid'=>$uid,
            'id' =>$chat_id
        ];
        $is_owner = Db::name('chatroom')->where($maps)->find();
        if(!$is_owner){
            json_return(201,'你不是房主，不能进行操作');
        }
        $ups = [
            'is_open'=>$is_open
        ];
        $result0 = Db::name('chatroom')->where($maps)->update($ups);
        if($is_open==0){
            $queue_arr = [];
            Cache::set('chatqueue_arr'.$chat_id,$queue_arr);
        }
        json_return(200,'成功',$ups);

    }

    /**
     * 房主拉黑某人
     */
    public function push_to_room(){
        $chat_id     =  input('post.chat_id');
        $uid         =  input('post.uid');
        $black_uid   =  input('post.black_uid');
        if(!$uid ||!$chat_id ||!$black_uid){
            json_return(204,'缺少参数');
        }
        $maps = [
            'uid'=>$uid,
            'id' =>$chat_id
        ];
        $is_owner = Db::name('chatroom')->where($maps)->find();
        if(!$is_owner){
            json_return(201,'你不是房主，不能进行操作');
        }
        $insert = [
            'uid'     =>$black_uid,
            'chat_id' =>$chat_id
        ];
        $black_info = Db::name('black')->where($insert)->find();
        if($black_info){
            json_return(201,'已经拉黑');
        }
        $result0 = Db::name('black')->insert($insert);
        if($result0){
            json_return(200,'成功');
        }else{
            json_return(201,'失败');
        }

    }

    /**
     * 获取红包详情
     */
    public function get_red_info(Request $request){
        $red_id = $request->post('red_id');
        $data = Db::name('red')
            ->alias('r')
            ->field('r.*,m.head,m.nickname')
            ->join('dl_member m','m.id=r.uid')
            ->where('r.id',$red_id)
            ->find();
        if(!$data){
            json_return(205,'暂无数据');
        }
        $rob_info = Db::name('red_rob')
            ->alias('r')
            ->field('r.*,m.head,m.nickname')
            ->join('dl_member m','m.id=r.uid')
            ->where('r.red_id',$red_id)
            ->select();
        $data['rob_info'] = $rob_info;
        json_return(200,'成功',$data);

    }













}